package event

import (
	"context"
	"math"

	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/code"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/client/event"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userrpc"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 列表
func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListLogic) List(req *types.EventListReq) (resp *types.EventListResData, err error) {
	if req.Page == 0 {
		req.Page = 1
	}

	if req.Size == 0 {
		req.Size = 10
	}

	u, err := l.svcCtx.SettingService.EventService.EventList(l.ctx, &event.EventListReq{
		Page:       req.Page,
		Size:       req.Size,
		BrandName:  req.BrandName, // 厂商名称
		EventNum:   req.EventNum,  // 事件编码
		Status:     req.Status,    // 状态,0:关,1:开
		MerchantId: 1,             // 商户ID
	})

	if err != nil {
		logc.Error(l.ctx, "List EventList err:", err)
		return nil, err
	}

	if u.Code != int64(code.SettingRpcSuccessful.Code()) {
		return nil, code.BusinessFailure
	}

	list := make([]types.EventListResItem, 0)
	userIdMap := map[int64]int64{}

	for _, v := range u.Data.List {
		userIdMap[v.OperatorId] = v.OperatorId
		list = append(list, types.EventListResItem{
			Id:           v.Id,
			MerchantId:   v.MerchantId,
			BrandType:    v.BrandType,
			BrandName:    v.BrandName,
			EventNum:     v.EventNum,
			ApiUrl:       v.ApiUrl,
			ApiToken:     v.ApiToken,
			Sort:         v.Sort,
			Status:       v.Status,
			OperatorId:   v.OperatorId,
			OperatorName: "",
			CreatedAt:    v.CreatedAt,
			UpdatedAt:    v.UpdatedAt,
		})
	}

	userIdList := make([]int64, 0)
	for _, v := range userIdMap {
		userIdList = append(userIdList, v)
	}

	if len(userIdList) > 0 {
		infoResp, err := l.svcCtx.UserServiceRPC.AdminUserNameList(l.ctx, &userrpc.AdminUserNameListRequest{IdList: userIdList})
		if err != nil {
			logc.Error(l.ctx, "UserServiceRPC.AdminUserNameList err:", err)
		}

		if err == nil && len(infoResp.AdminUserNameList) > 0 {
			userResMap := map[int64]string{}
			for _, v := range infoResp.AdminUserNameList {
				userResMap[v.Id] = v.Nickname
			}

			if len(userResMap) > 0 {
				for index, v := range list {
					if value, ok := userResMap[v.OperatorId]; ok {
						list[index].OperatorName = value
					}
				}
			}
		}
	}

	resp = &types.EventListResData{
		List: list, // 列表
		Pagination: types.Pagination{
			PageSize:  int32(req.Size),
			Page:      int32(req.Page),
			Total:     u.Data.Count,
			TotalPage: int64(math.Ceil(float64(u.Data.Count) / float64(req.Size))),
		}, // 分页信息
	}
	return
}
